package com.hhwy.framework.configure.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import com.hhwy.framework.cache.Cache;
import com.hhwy.framework.util.IoTools;

@Component
public class SystemConfigure {

	Logger log = LoggerFactory.getLogger(SystemConfigure.class);

	private static final String CLASS_RESOURCE_PATTERN = "/**/*-config.properties";
	
	public static Set<Resource> resSet= new HashSet<Resource>();
	//记录通用配置选项，优先从环境变量获取
	private static List<String> commonOption = new ArrayList<>();
	/**
	 * 初始化, 获取配置信息
	 */
	public void init() throws IOException{
		
		initProperties();
		//从数据库加载系统配置
		BasicConfigureLoader.getInst().loadSystemConfigureFromDB();
		//检查环境变量，相同的配置项，以环境变量优先
		//checkEnv();
		//加载语言配置到缓存中
		//BasicConfigureLoader.getInst().loadLanguageConfigureFromDB();
	}
	
	/**
	 * checkEnv(系统配置最终以环境变量优先使用)<br/> 
	 * void
	 * @exception 
	 * @since  1.0.0
	*/
	private void checkEnv() {
		Map<String,String> env = System.getenv();
		
		for(String key : commonOption){
			String eKey = key.replace(".", "_");
			if(StringUtils.isNotBlank(env.get(eKey)))
				Cache.setSystemConfig(key.toLowerCase(), env.get(eKey));
			else if(StringUtils.isNotBlank(env.get(eKey.toUpperCase()))){
				Cache.setSystemConfig(key.toLowerCase(), env.get(eKey.toUpperCase()));
			}
		}
	}
	/**
	 * checkEnv：检查环境变量是否包含key选项<br/> 
	 * void
	 * @exception 
	 * @since  1.0.0
	*/
	private String getEnv(String key ) {
		Map<String,String> env = System.getenv();
		
		String eKey = key.replace(".", "_");
		if(StringUtils.isNotBlank(env.get(eKey))){
			return env.get(eKey);
		}else if(StringUtils.isNotBlank(env.get(eKey.toUpperCase()))){
			return env.get(eKey.toUpperCase());
		}else
			return null;
	}

	/**
	 * initProperties: 加载db.properties、system-config.properties等<br/>
	 * void
	 * 
	 * @throws IOException
	 * @exception
	 * @since 1.0.0
	 */
	public void initProperties() throws IOException {
		try {
			Resource[] resources = IoTools.scan("/config", CLASS_RESOURCE_PATTERN);
			for (int i = 0; i < resources.length; i++) {
				resSet.add(resources[i]);
				loadSystemConfig(resources[i]);
			}
			
			
			Resource[] dbs = IoTools.scan("/", "db.properties");
			if (dbs.length > 0) {
				Resource db = dbs[0];
				resSet.add(db);
				loadSystemConfig(db );
			}
			Resource[] systems = IoTools.scan("/", "system-config.properties");
			if(systems.length > 0){
				Resource system = systems[0];
				resSet.add(system);
				loadSystemConfig(system );
			}
			Resource[] bases = IoTools.scan("/", "base-config.properties");
			if (bases != null && bases.length > 0){
				resSet.add(bases[0]);
				loadSystemConfig(bases[0] );
			}
			
			
		} catch (Throwable e) {
			log.error("SystemConfigure.init has error", e);
		}

	}

	private void loadSystemConfig(Resource resource ) {
		try {
			Properties systemProps = PropertiesLoaderUtils
					.loadProperties(resource);

			Iterator<Object> it = systemProps.keySet().iterator();
			while (it.hasNext()) {
				String key = it.next().toString();
				
				String value = systemProps.getProperty(key);
				//记录通用配置选项，优先从环境变量获取
				if(getEnv(key) != null){
					value = getEnv(key);
					commonOption.add(key.toLowerCase());
				}
				Cache.setSystemConfig(key.toLowerCase(), value);
				
				log.info("cache::key==" + key + " value="
						+ Cache.getSystemConfig(key));
			}

		} catch (Throwable e) {
			e.printStackTrace();
			log.error("SystemConfigure.loadSystemConfig has error", e);
		}

	}

}
